class_name ProgressBarWithBuffer
extends Node

#region 属性
@export var attenuation_time:float = 0.5
var max_value:float = 0
var cur_value:float = 0
var tween:Tween
#endregion
#region 字段
#endregion
#region 信号
#endregion

#region 基类方法
func init(_cur_value:float,_max_value:float):
	max_value = _max_value
	_on_add(clampf(_cur_value,0,max_value))
func change_value(value:float):
	value = max(0,value)
	if cur_value <= value:
		_on_add(value)
	else:
		_on_sub(value)
func change_max_value(new_max_value:float):
	_on_max_value_changed(new_max_value)
#endregion
#region 公共方法
#endregion
#region 私有方法
func _on_sub(_cur_value:float):
	if tween and tween.is_valid():
		tween.kill()
	tween = create_tween()
	self.cur_value = _cur_value
	var fill_value = cur_value / max_value
	%PBFore.value = fill_value
	tween.tween_property(%PBBack,"value",fill_value,attenuation_time).set_ease(Tween.EASE_OUT)
func _on_add(_cur_value:float):
	if tween and tween.is_valid():
		tween.kill()
	tween = create_tween()
	self.cur_value = _cur_value
	var fill_value = cur_value / max_value
	%PBBack.value = fill_value
	tween.tween_property(%PBFore,"value",fill_value,attenuation_time).set_ease(Tween.EASE_OUT)
func _on_max_value_changed(new_max_value):
	if tween and tween.is_valid():
		tween.kill()
	tween = create_tween()
	var last_max_value = max_value
	max_value = new_max_value
	var fill_value = cur_value / max_value
	if cur_value / (last_max_value + 1) <= cur_value / (max_value + 1):
		_on_add(cur_value)
	else:
		_on_sub(cur_value) 
#endregion
#region 生命周期函数
#endregion
